package com.demo.cms.action.manage;

import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.demo.core.context.RefreshModel;
import com.demo.core.context.event.RefreshEvent;
import com.demo.core.model.Site;
import com.demo.core.model.SiteGroup;
import com.demo.core.service.base.SiteGroupService;
import com.demo.core.service.base.SiteService;
import com.demo.security.annotation.function.Function;
import com.demo.webapp.action.PageAction;
import com.demo.webapp.cache.model.WebCacheModel;
import com.demo.webapp.cache.service.WebCacheService;
import com.demo.webapp.context.MultisiteContextHolder;
import com.demo.webapp.filter.MultisiteFilter;

/**
 * 站点管理Action
 * @author ryuu.kk
 *
 */
@Function(id = 100500, pid = 10, name="站点管理", code = "manage.site")
public class SiteAction extends PageAction implements ApplicationContextAware {

	/**
	 * 版本序列化ID
	 */
	private static final long serialVersionUID = -2704331427569780693L;

	/**
	 * 主键ID
	 */
	private Long id;
	
	/**
	 * 站点模型
	 */
	private Site site;
	
	/**
	 * 站点状态
	 */
	private boolean open;
	
	/**
	 * 是否允许站点缓存
	 */
	private boolean allow;
	
	/**
	 * 默认跳转地址
	 */
	private String defaultUrl;
	
	/**
	 * 站点前台访问的URL后缀
	 */
	private String suffix;
	
	/**
	 * 站点服务
	 */
	private SiteService siteService;
	
	/**
	 * 站点分组模型
	 */
	private List<SiteGroup> siteGroupList;
	
	/**
	 * 站点分组服务
	 */
	private SiteGroupService siteGroupService;
	
	/**
	 * 缓存服务服务
	 */
	private WebCacheService<Long> webCacheService;
	
	/**
	 * Spring容器上下文
	 */
	private ApplicationContext applicationContext;
	
	/**
	 * url缓存模型列表
	 * 缓存在Action中
	 */
	private List<WebCacheModel> webCacheModelList;
	
	/**
	 * 站点信息维护
	 */
	@Function(id = 100540, pid = 100500, name="站点编辑", code = "manage.site.edit")
	public String edit() {
		
		// 取得站点ID
		Site site = MultisiteContextHolder.getSite();
		Long siteId = site.getId();
		
		this.site = siteService.find(siteId);
		this.siteGroupList = siteGroupService.findAll();
		
		return SUCCESS;
	}

	/**
	 * 站点信息维护-保存
	 * @return String
	 */
	@Function(id = 100530, pid = 100500, name="站点保存", code = "manage.site.save")
	public String save() {
		
		// 取得站点ID
		Long siteId = MultisiteContextHolder.getSite().getId();
		Site siteTemp = siteService.findByDomain(site.getDomain());
		if (siteTemp != null && !siteTemp.getId().equals(siteId)) {
			// 站点使用了其他站点的域名
			addActionError(getText("site.save.exist", "站点域名已经存在,不能重复注册."));
			return INPUT;
		}
		
		// 更新站点信息
		siteService.update(siteId, site);
		// 更新站点持有者信息
		siteService.updateOwner(siteId, site);
		// 刷新多站点模型缓存
		MultisiteFilter.refresh();
		// 定义刷新事件模型
		RefreshModel model = new RefreshModel();
		model.setType(RefreshModel.MODEL_TYPE_METHOD);
		// 定义刷新事件
		RefreshEvent event = new RefreshEvent(model) {
			/**
			 * 版本序列化ID
			 */
			private static final long serialVersionUID = -1928151224804257473L;
		};
		
		applicationContext.publishEvent(event);
		addActionMessage(getText("site.save.success", "站点信息已经成功更新"));
		return CALLBACK;
	}

	/**
	 * 站点缓存设置-展示
	 * @return String
	 */
	@Function(id = 100570, pid = 100500, name="WEB缓存设置", code = "manage.site.cache")
	public String cache() {
		
		Site site = getSite();
		
		this.webCacheModelList = webCacheService.queryCache(site.getId());
		// 获得站点配置
		Map<String, Object> config = getConfiguration();
		Object obj = config.get(com.demo.webapp.config.Constants.APP_WEBCACHE_SWITCH);
		allow = (obj == null ? false : Boolean.parseBoolean(obj.toString()));
		
//		// 得到WEB-CACHE对象模型
//		Config config = configService.query(site.getId(), com.demo.webapp.config.Constants.CONFIG_WEBCACHE_KEY);
//		if (config == null) {
//			// 新建一个站点级别缓存配置
//			config = new Config();
//			config.setEnabled(Boolean.TRUE);
//			config.setName(com.demo.webapp.config.Constants.CONFIG_WEBCACHE_KEY);
//			config.setSiteId(site.getId());
//			config.setType(Config.CONFIG_TYPE_SITE);
//			config.setTitle(getText("site.cache", "站点WEB缓存"));
//			config.setStatus(Config.STATUS_NORMAL);
//			config.setI18n("zh_CN");
//			configService.save(config);
//		}
//		List<ConfigItem> items = config.getConfigItemList();
//		if (items != null) {
//			
//		}
		//Map<String, Object> siteConfig = getConfiguration();
		// 取得允许缓存和拒绝缓存URL地址列表
		//this.webCacheModelList = (List<WebCacheModel>) siteConfig.get(Constants.APP_WEBCACHE_MODEL_LIST);
		
		return SUCCESS;
	}
	
	/**
	 * 改变缓存设置
	 * @return String
	 */
	@Function(id = 100580, pid = 100500, name="WEB缓存更新", code = "manage.site.cachechange")
	public String cacheChange() {
		
		Site site = getSite();
		Long siteId = site.getId();
		
		//Map<String, Object> config = getConfiguration();
		//@SuppressWarnings("unchecked")
		//List<WebCacheModel> modelList = (List<WebCacheModel>) config.get(com.demo.webapp.config.Constants.APP_WEBCACHE_MODEL_LIST);
		
		webCacheService.saveCache(siteId, this.webCacheModelList);
//		getWebCacheModelList();
//		if (webCacheModelList != null && webCacheModelList.size() > 0) {
//			List<String> allowList = new ArrayList<String>();
//			for (WebCacheModel model : webCacheModelList) {
//				for (WebCacheModel m : modelList) {
//					if (model.getId().equals(m.getId())) {
//						model.setName(m.getName());
//						model.setTitle(m.getTitle());
//					}
//				}
//				if (model.isAllow()) {
//					allowList.add(model.getUrl());
//				}
//			}
//			config.put(Constants.APP_CACHE_MODEL_LIST, webCacheModelList);
//			config.put(Constants.APP_CACHE_ALLOW_URL, allowList.toArray(new String[]{}));
//			// 写入缓存持久文件
//		}
		addActionMessage("站点缓存更新成功");
		return CALLBACK;
	}
	
	/**
	 * 删除WEB缓存项
	 * @return String
	 */
	@Function(id = 100590, pid = 100500, name="WEB缓存删除", code = "manage.site.cachedelete")
	public String cacheDelete() {
		Site site = getSite();
		if (id != null) {
			// 删除一个WEB缓存
			webCacheService.removeCache(site.getId(), id);
			// 站点缓存匹配地址
			String[] cacheUrls = webCacheService.cacheUrls(site.getId());
			// 获得站点配置,并同步它
			Map<String, Object> config = getConfiguration();
			synchronized (config){
				config.put(com.demo.webapp.config.Constants.APP_WEBCACHE_URL, cacheUrls);
			}
			addActionMessage("站点缓存已成功删除.");
		} else {
			addActionMessage("未找到要删除的站点缓存.");
		}
		
		// 写入缓存持久文件
		return CALLBACK;
	}
	
	/**
	 * WEB缓存状态变更开关
	 * @return String
	 */
	// 与cache共享同一个@Function的ID 即两个方法同步授权
	@Function(id = 100570, pid = 100500, name="WEB缓存设置", code = "manage.site.cache")
	public String cacheSwitch() {
		// 得到当前站点
		Site site = getSite();
		if (getAllow()) {
			// 开启站点WEB缓存
			webCacheService.enable(site.getId());
			addActionMessage(getText("config.webcache.enabled"));
		} else {
			// 关闭站点WEB缓存
			webCacheService.disable(site.getId());
			addActionMessage(getText("config.webcache.disabled"));
		}
		// 同步站点缓存开关配置
		Map<String, Object> config = getConfiguration();
		synchronized (config){
			config.put(com.demo.webapp.config.Constants.APP_WEBCACHE_SWITCH, getAllow());
		}
		
		return "result";
 	}
	
	/**
	 * 站点开放的Action
	 * □ 100991=Config_global
	 * @return String
	 */
	@Function(id = 100992, pid = 100991, name="站点状态设置", code = "manage.site.open")
	public String status() {
		
		// 已经关闭,可以打开,否则关闭.
		if (isOpen()) {
			addActionMessage(getText("site.open.success"));
			siteService.open(site.getId());
		} else {
			addActionMessage(getText("site.close.success"));
			siteService.close(site.getId(), getDefaultUrl());
		}
		// 刷新多站点模型缓存
		MultisiteFilter.refresh();
		// 使用简单结果
		return "result";
	}
	
	/**
	 * 站点前台URL后缀的Action
	 * □ 100991=Config_global
	 * @return String
	 */
	@Function(id = 100993, pid = 100991, name="站点后缀设置", code = "manage.site.suffix")
	public String suffix() {
		
		Site site = getSite();
		int count = siteService.updateSuffix(site.getId(), suffix);
		if (count > 0) {
			addActionMessage(getText("site.suffix.success", new String[]{suffix}));
		} else {
			addActionMessage(getText("site.suffix.fault"));
		}
		// 刷新多站点模型缓存
		MultisiteFilter.refresh();
		// 使用简单结果
		return "result";
	}
	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Site getSite() {
		if (site == null) {
			site = super.getSite();
		}
		return site;
	}

	public void setSite(Site site) {
		this.site = site;
	}
	
	public boolean isOpen() {
		return open;
	}

	public void setOpen(boolean open) {
		this.open = open;
	}

	public boolean getAllow() {
		return allow;
	}

	public void setAllow(boolean allow) {
		this.allow = allow;
	}

	public String getDefaultUrl() {
		return defaultUrl;
	}

	public void setDefaultUrl(String defaultUrl) {
		this.defaultUrl = defaultUrl;
	}

	public String getSuffix() {
		return suffix;
	}

	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}

	public List<WebCacheModel> getWebCacheModelList() {
		return webCacheModelList;
	}

	public void setWebCacheModelList(List<WebCacheModel> webCacheModelList) {
		this.webCacheModelList = webCacheModelList;
	}

	public List<SiteGroup> getSiteGroupList() {
		return siteGroupList;
	}

	public void setSiteService(SiteService siteService) {
		this.siteService = siteService;
	}

	public void setWebCacheService(WebCacheService<Long> webCacheService) {
		this.webCacheService = webCacheService;
	}

	public void setSiteGroupService(SiteGroupService siteGroupService) {
		this.siteGroupService = siteGroupService;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}
}
